package com.zhaoyh.websocket;

import org.springframework.web.socket.*;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * websocket处理器：功能实现的核心代码编写类
 * @author 祥霸
 * @date 2019/4/15
 */
public class MyWebSocketHandler implements WebSocketHandler {
    /**
     * 定义一个全局的初始化值count=0,记录连接数
     */
    private static int count = 0;

    /**
     * 记录所有的客户端连接
     */

    private volatile static List<WebSocketSession> sessions = Collections.synchronizedList(new ArrayList());


    public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
        count++;
        sessions.add(webSocketSession);
    }

    /**
     * 消息处理，在客户端通过Websocket API发送的消息会经过这里，然后进行相应的处理
     * @author 祥霸
     * @date 2019/4/15
     * @params webSocketSession
    		webSocketMessage
     * @return void
     */
    public void handleMessage(WebSocketSession webSocketSession, WebSocketMessage<?> webSocketMessage) throws Exception {

        String data = webSocketMessage.getPayload().toString();
        System.out.println("客户端" + webSocketMessage.getPayload().toString());
        if(!data.equals("B")) {
            sessions.remove(webSocketSession);
            try {
                for (WebSocketSession ws : sessions) {
                    if (ws.isOpen()) {
                        synchronized (ws) {
                            ws.sendMessage(new TextMessage("" + data));
                            System.out.println("服务端" + data);
                        }

                    }
                }
            } catch (IOException e) {
                e.printStackTrace();

            }
        }

    }

    /**
     * 消息传输错误处理
     * @author 祥霸
     * @date 2019/4/15
     * @params webSocketSession
    		throwable
     * @return void
     */
    public void handleTransportError(WebSocketSession webSocketSession, Throwable throwable) throws Exception {
        if(webSocketSession.isOpen()){
            sessions.remove(webSocketSession);
            webSocketSession.close();
        }
    }

    public void afterConnectionClosed(WebSocketSession webSocketSession, CloseStatus closeStatus) throws Exception {
        sessions.remove(webSocketSession);
        if (webSocketSession.isOpen()){
            webSocketSession.close();
        }
        count = count-1;
        System.out.println(count);
    }

    public boolean supportsPartialMessages() {
        return false;
    }
}
